package com.polaris.live.utils

import android.view.View
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil
import org.libpag.PAGFile
import org.libpag.PAGImageView
import java.io.File

/**
 * PagUtils
 *
 * @author Created by lucas on 2024/12/3 09:27
 * @since 1.0.0
 */

/**
 * 循环播放Pag动画
 */
fun PAGImageView.playAsync(
    lifecycleScope: LifecycleCoroutineScope,
    path: String?,
    block: PAGImageView.(PAGFile) -> Unit = { setRepeatCount(-1) }
) {
    if (path.isNullOrEmpty()) {
        return
    }

    DownLoadFileUtil.loadPag(lifecycleScope, path) { _, realPath ->
        val pageFile = PAGFile.Load(realPath) ?: return@loadPag
        block(pageFile)
        composition = pageFile
        play()
    }
}

/**
 * 加载Pag动画
 */
fun PAGImageView.loadAsync(
    lifecycleScope: LifecycleCoroutineScope,
    path: String,
    block: PAGImageView.(PAGFile) -> Unit = { setRepeatCount(-1) },
) {
    DownLoadFileUtil.loadPag(lifecycleScope, path) { nPath, realPath ->
        if (path == nPath) {
            val pageFile = PAGFile.Load(realPath) ?: return@loadPag
            block(pageFile)
            composition = pageFile
        }
    }
}

/**
 * 循环播放Pag动画
 */
fun PAGImageView.playAsync2(
    lifecycleScope: LifecycleCoroutineScope,
    path: String?,
    block: PAGImageView.(PAGFile) -> Unit = { setRepeatCount(-1) },
    playCallBack: () -> Unit,
) {
    if (path.isNullOrEmpty()) {
        return
    }

    DownLoadFileUtil.loadPag(lifecycleScope, path) { nPath, realPath ->
        if (path == nPath) {
            val pageFile = PAGFile.Load(realPath) ?: return@loadPag
            block(pageFile)
            composition = pageFile
            play()
            playCallBack.invoke()
        }
    }
}

/**
 * 通过owner播放Pag动画
 */
fun PAGImageView.playAsyncWithOwner(owner: LifecycleOwner?, path: String?) {
    if (path.isNullOrEmpty()) {
        return
    }

    val pagPath = FileUtils.getFilePath(FileUtils.getPagFile(), path)
    if (!File(pagPath).exists()) {
        owner?.lifecycleScope?.also {
            playAsync(it, path) {
                visibility = View.VISIBLE
            }
        }

        return
    }

    visibility = View.VISIBLE
    this.path = pagPath
    play()
}